package com.automation.app;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;

public class DianPingAutomation {

    private AndroidDriver driver;
    private WebDriverWait wait;
    private int processedShops = 0;
    private final int MAX_SHOPS = 10; // 最大处理商户数

    public DianPingAutomation(AndroidDriver driver) {
        this.driver = driver;
        this.wait = new WebDriverWait(driver, Duration.ofSeconds(15));
    }

    public void run() {
        // 1. 确保在商户列表页面
        wait.until(ExpectedConditions.presenceOfElementLocated(
                AppiumBy.className("android.support.v7.widget.RecyclerView")
        ));

        while (processedShops < MAX_SHOPS) {
            // 2. 定位商户列表容器
            WebElement shopListContainer = findShopListContainer();

            // 3. 获取当前页商户项
            List<WebElement> shopItems = getCurrentPageShopItems(shopListContainer);
            if (shopItems.isEmpty()) break;

            // 4. 遍历商户
            for (WebElement shopItem : shopItems) {
                if (processedShops >= MAX_SHOPS) break;

                // 5a. 点击商户项
                shopItem.click();
                processShopDetail();
                processedShops++;
            }

            // 6. 滚动加载更多
            scrollToLoadMore(shopListContainer);
        }
    }

    private WebElement findShopListContainer() {
        // 通过特征定位商户列表RecyclerView（高度最大）
        List<WebElement> recyclers = driver.findElements(
                AppiumBy.className("android.support.v7.widget.RecyclerView")
        );

        WebElement maxHeightRecycler = null;
        int maxHeight = 0;

        for (WebElement recycler : recyclers) {
            Dimension size = recycler.getSize();
            if (size.getHeight() > maxHeight) {
                maxHeight = size.getHeight();
                maxHeightRecycler = recycler;
            }
        }
        return maxHeightRecycler;
    }

    private List<WebElement> getCurrentPageShopItems(WebElement container) {
        // 获取直接子元素（商户项）
        return container.findElements(AppiumBy.xpath("./*"));
    }

    private void processShopDetail() {
        // 5b. 等待详情页加载
        wait.until(ExpectedConditions.presenceOfElementLocated(
                AppiumBy.xpath("//*[contains(@text, '商家信息') or contains(@text, '评分')]")
        ));
        test();
        // 5c. 停留查看
        sleep(3000);

        // 5d. 进入评价页
        try {
            driver.findElement(AppiumBy.xpath("//*[contains(@text, '评价')]")).click();
            processReviews();
        } catch (Exception e) {
            System.out.println("未找到评价页入口");
        }

        // 5i. 返回列表
        driver.pressKey(new KeyEvent(AndroidKey.BACK));
        wait.until(ExpectedConditions.presenceOfElementLocated(
                AppiumBy.className("android.support.v7.widget.RecyclerView")
        ));
    }

    private void processReviews() {
        // 5d. 等待评价页加载
        wait.until(ExpectedConditions.presenceOfElementLocated(
                AppiumBy.xpath("//*[contains(@text, '带图') or contains(@text, '视频')]")
        ));

        // 5e. 筛选带图/视频评价
        try {
            driver.findElement(AppiumBy.xpath("//*[contains(@text, '带图')]")).click();
            sleep(2000);
            driver.findElement(AppiumBy.xpath("//*[contains(@text, '视频')]")).click();
            sleep(2000);
        } catch (Exception e) {
            System.out.println("未找到筛选选项");
        }

        // 5f. 检测并保存高质量图片（模拟）
        System.out.println("检测到高质量图片，已保存");

        // 5g. 创建笔记（模拟）
        driver.findElement(AppiumBy.id("com.dianping.v1:id/create_note_btn")).click();
        sleep(1500);
        driver.findElement(AppiumBy.xpath("//*[contains(@text, '推荐拼图')]")).click();
        driver.findElement(AppiumBy.xpath("//*[contains(@text, '美食')]")).click();

        // 5h. 保存草稿
        driver.findElement(AppiumBy.id("com.dianping.v1:id/save_draft_btn")).click();
        sleep(1000);

        // 返回详情页
        driver.pressKey(new KeyEvent(AndroidKey.BACK));
    }

    private void scrollToLoadMore(WebElement container) {
        // 6. 滚动加载更多
        Dimension size = driver.manage().window().getSize();
        int startY = (int) (size.height * 0.8);
        int endY = (int) (size.height * 0.2);
        int centerX = size.width / 2;

        new TouchAction<>(driver)
                .press(PointOption.point(centerX, startY))
                .waitAction(WaitOptions.waitOptions(Duration.ofMillis(1000)))
                .moveTo(PointOption.point(centerX, endY))
                .release()
                .perform();

        sleep(3000); // 等待加载
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void test(){
        try {

            // d. 进入评价页查看带图/视频评价
            driver.findElement(AppiumBy.accessibilityId("评价")).click();
            driver.findElement(AppiumBy.accessibilityId("查看全部")).click();

            // 等待评价页面加载
            new WebDriverWait(driver, Duration.ofSeconds(10))
                    .until(ExpectedConditions.presenceOfElementLocated(
                            AppiumBy.xpath("//android.widget.TextView[contains(@text, '带图') or contains(@text, '视频')]")
                    ));

            // e. 检测并保存高质量图片
            List<WebElement> images = driver.findElements(AppiumBy.className("android.widget.ImageView"));
            for (int i = 0; i < Math.min(images.size(), 3); i++) { // 保存前3张
                File screenshot = images.get(i).getScreenshotAs(OutputType.FILE);
                saveImage(screenshot, "review_image_" + i + ".png");
            }

            // f. 创建笔记
            driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text='发笔记']")).click();

            // 等待笔记编辑页面
            new WebDriverWait(driver, Duration.ofSeconds(5))
                    .until(ExpectedConditions.presenceOfElementLocated(
                            AppiumBy.id("com.dianping.v1:id/editor_container")
                    ));

            // 添加截图
            driver.findElement(AppiumBy.id("com.dianping.v1:id/add_image_btn")).click();
            driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text='从相册选择']")).click();
            // 这里需要实际的文件选择操作，简化处理
            Thread.sleep(2000);

            // g. 生成拼图并选择话题
            driver.findElement(AppiumBy.id("com.dianping.v1:id/puzzle_btn")).click();
            driver.findElement(AppiumBy.id("com.dianping.v1:id/topic_selection")).click();
            driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text='美食推荐']")).click();

            // h. 保存为草稿
            driver.findElement(AppiumBy.id("com.dianping.v1:id/save_draft_btn")).click();
            new WebDriverWait(driver, Duration.ofSeconds(3))
                    .until(ExpectedConditions.presenceOfElementLocated(
                            AppiumBy.xpath("//android.widget.Toast[@text='已保存到草稿']")
                    ));

            // i. 返回商户列表
            // 先返回笔记编辑页
            driver.pressKey(new KeyEvent(AndroidKey.BACK));
            // 再返回详情页
            driver.pressKey(new KeyEvent(AndroidKey.BACK));
            // 最后返回列表页
            driver.findElement(AppiumBy.accessibilityId("Navigate up")).click();

            // j. 等待列表页加载
            new WebDriverWait(driver, Duration.ofSeconds(10))
                    .until(ExpectedConditions.presenceOfElementLocated(
                            AppiumBy.id("com.dianping.v1:id/recycler_view")
                    ));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.quit();
        }
    }

    private static void saveImage(File imageFile, String fileName) throws IOException {
        Path destination = Paths.get("screenshots", fileName);
        Files.createDirectories(destination.getParent());
        Files.copy(imageFile.toPath(), destination);
    }


}